package com.cdm.forum.controller;

import com.cdm.forum.common.Result;
import com.cdm.forum.common.ResultCode;
import com.cdm.forum.config.AppConfig;
import com.cdm.forum.exception.ApplicationException;
import com.cdm.forum.model.Article;
import com.cdm.forum.model.Board;
import com.cdm.forum.model.User;
import com.cdm.forum.service.IArticleService;
import com.cdm.forum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(tags = "帖子接口")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private IBoardService boardService;

    @Autowired
    private IArticleService articleService;
    @Autowired
    private HttpSession httpSession;

    /**
     * 发布帖子
     *
     * @param boardId 板块Id
     * @param title   标题
     * @param content 内容
     * @return
     */
    @ApiOperation("添加帖子")
    @PostMapping("/createArticle")
    public Result createArticle(HttpServletRequest request,
                                @ApiParam("板块Id") @RequestParam("boardId") @NonNull Long boardId,
                                @ApiParam("标题") @RequestParam("title") @NonNull String title,
                                @ApiParam("内容") @RequestParam("content") @NonNull String content) {

        //验证用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            //用户已经禁言
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }

        //板块的校验
        Board board = boardService.selectByPrimaryKey(boardId);
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            //抛出异常
            return Result.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        //封装对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        //写入数据库
        articleService.createArticle(article);
        return Result.success();
    }

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllListArticle")
    public Result<List<Article>> getAllListArticle(@ApiParam("板块id") @RequestParam(value = "boardId", required = false) Long boardId) {
        //非必传参数

        List<Article> articles = null;
        if (boardId == null) {
            articles = articleService.selectAll();

        } else {
            articles = articleService.selectBoardById(boardId);
        }
        //校验
        if (articles == null) {
            //这里如果返回null，那么前端返回的是“null”字符串
            articles = new ArrayList<>();
        }
        //响应结果
        return Result.success(articles);
    }

    /**
     * 获取板块信息
     *
     * @param id
     * @return
     */
    @ApiOperation("获取板块信息")
    @GetMapping("/selectBoardById")
    public Result<Board> selectBoardById(@ApiParam("板块id") @RequestParam("id") @NonNull Long id) {
        //调用service
        Board board = boardService.selectByPrimaryKey(id);
        //校验
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        //返回结果
        return Result.success(board);
    }

    @ApiOperation("根据帖子id查询帖子信息")
    @GetMapping("/details")
    public Result<Article> getDetails(HttpServletRequest request,
                                      @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用Service层
        Article article = articleService.selectDetailById(id);
        if (article == null) {
            //返回错误信息
            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断是否为作者
        if (user.getId() == article.getUserId()) {
            //标识为作者
            article.setIsOwn(true);
        }
        return Result.success(article);
    }


    @ApiOperation("根据帖子id修改帖子")
    @PostMapping("/modifyArticle")
    public Result modifyArticle(HttpServletRequest request,
                                         @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                                         @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                                         @ApiParam("帖子内容") @RequestParam("content") @NonNull String content) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户状态
        if (user.getState() == 1) {
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }

        //查询帖子详细信息
        Article article = articleService.selectById(id);
        //判断帖子是否有效
        if (article == null) {
            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断帖子状态是否异常
        if(article.getDeleteState() == 1 || article.getState() == 1){
            log.info("id+" + id +"title" + title + "content" + content);
            log.info("状态异常DeleteState：" + article.getDeleteState()+ "State+" + article.getState());
            return Result.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //判断用户是不是作者
        if (user.getId() != article.getUserId()) {
            return Result.failed(ResultCode.FAILED_FORBIDDEN);
        }

        //更新帖子
        articleService.modifyArticle(id, title, content);

        //打印日志
        log.info("帖子更新成功 帖子id:" + id + ",帖子title:" + title + ",帖子content:" + content);
        return Result.success();
    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUpById")
    public Result thumbsUpById(HttpServletRequest request,
                               @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //判断用户是否被禁言
        if(user.getState() == 1){
            //返回结果
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }

        //查询帖子详细信息
        Article article = articleService.selectById(id);
        //判断帖子是否有效
        if (article == null) {
            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断帖子状态是否异常
        if(article.getDeleteState() == 1 || article.getState() == 1){
           return Result.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        //调用service
        articleService.thumbsUpById(id);
        return Result.success();

    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public Result deleteById(HttpServletRequest request,
            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {

        //校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }

        //查询帖子详细
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1 || article.getState() == 1) {
            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //判断用户是否为作者
        if(user.getId() != article.getUserId()) {
            return Result.failed(ResultCode.FAILED_FORBIDDEN);
        }

        //调用service
        articleService.deleteById(id);
        return Result.success();

    }

    @ApiOperation("获取用户帖子列表")
    @GetMapping("getAllByUserId")
    public Result<List<Article>> getAllByUserId(HttpServletRequest request,
            @ApiParam("用户id") @RequestParam(value = "userId", required = false) Long userId) {

        if (userId == null) {
            //从session里面获取用户id
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }

        //调用service
        List<Article> articles = articleService.selectByUserId(userId);

        return Result.success(articles);
    }
}